// 随访记录详情页面
const auth = require('../../../utils/auth.js');
const moment = require('../../../utils/moment');

Page({
  data: {
    followupId: null,
    followup: null,
    loading: true
  },

  onLoad: function(options) {
    if (options.id) {
      this.setData({
        followupId: options.id
      });
      this.loadFollowupDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载随访详情
  loadFollowupDetail: function() {
    this.setData({ loading: true });
    
    wx.request({
      url: `${getApp().globalData.apiBaseUrl}/followup_records/${this.data.followupId}`,
      method: 'GET',
      header: { 'Authorization': `Bearer ${auth.getToken()}` },
      success: (res) => {
        this.setData({ loading: false });
        if (res.statusCode === 200) {
          const result = res.data;
          if (result.success) {
            this.setData({
              followup: result.data
            });
          } else {
            wx.showToast({
              title: result.message || '加载失败',
              icon: 'none'
            });
            setTimeout(() => {
              wx.navigateBack();
            }, 1500);
          }
        } else {
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      },
      fail: (error) => {
        this.setData({ loading: false });
        console.error('加载随访详情失败:', error);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    });
  },

  // 格式化日期
  formatDate: function(dateString) {
    if (!dateString) return '';
    return moment(dateString).format('YYYY-MM-DD');
  },

  // 格式化时间
  formatTime: function(timeString) {
    if (!timeString) return '';
    return timeString;
  },

  // 格式化日期时间
  formatDateTime: function(dateTimeString) {
    if (!dateTimeString) return '';
    return moment(dateTimeString).format('YYYY-MM-DD HH:mm');
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
});
